package com.sophie.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @Author: Rowena
 * @CreateTime: 2024-09-13 15:56:37
 * @Version: 1.0
 */

@WebFilter(urlPatterns = {"/main.jsp", "/object.jsp", "/individual.jsp","/ZoneServlet?method=objectZone","/FollowServlet","/CommentServlet?method=addComment"})
public class MyFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("filter init");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
        HttpSession session = httpRequest.getSession(false); // 不创建新会话
        String uri = httpRequest.getRequestURI();
        System.out.println("uri = " + uri);
        if (uri.endsWith("register")||uri.endsWith("login")||uri.endsWith("register.jsp")||uri.endsWith("login.jsp")){
            filterChain.doFilter(httpRequest, httpResponse);
        }else {
            // 检查Session中是否存在用户信息，这里仅为示例，实际情况中你需要根据实际情况来检查
            if (session == null || session.getAttribute("user") == null) {
                // 用户未登录，重定向到登录页面
                httpResponse.sendRedirect(httpRequest.getContextPath() + "/login.jsp");
            } else {
                // 用户已登录，继续请求链
                filterChain.doFilter(httpRequest, httpResponse);
            }
        }
    }

    @Override
    public void destroy() {
        System.out.println("filter destroy");
    }
}
